package com.mazaiting.instructions.loads;

import com.mazaiting.instructions.base.Index8Instruction;
import com.mazaiting.instructions.base.NoOperandsInstruction;
import com.mazaiting.rtda.MtFrame;

/**
 * 加载指令从局部变量表获取变量，然后推入操作数栈顶
 *
 * @author mazaiting
 * @since 2021/8/14
 */
public class ILoadInstruction {

    /**
     * 加载指令从局部变量表获取变量，然后推入操作数栈顶
     * @param frame 栈帧
     * @param index 索引
     */
    private static void load(MtFrame frame, int index) {
        // 从局部变量表获取变量
        int num = frame.getLocalVars().getInt(index);
        // 推入操作数栈顶
        frame.getOperandStack().pushInt(num);
    }

    public static class ILoad extends Index8Instruction {
        @Override
        public void execute(MtFrame frame) {
            load(frame, index);
        }

        @Override
        public String toString() {
            return "iload " + index;
        }
    }

    public static class ILoad0 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            load(frame, 0);
        }

        @Override
        public String toString() {
            return "iload_0";
        }
    }

    public static class ILoad1 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            load(frame, 1);
        }

        @Override
        public String toString() {
            return "iload_1";
        }
    }

    public static class ILoad2 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            load(frame, 2);
        }

        @Override
        public String toString() {
            return "iload_2";
        }
    }

    public static class ILoad3 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            load(frame, 3);
        }

        @Override
        public String toString() {
            return "iload_3";
        }
    }

    public static class ILoad4 extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            load(frame, 4);
        }

        @Override
        public String toString() {
            return "iload_4";
        }
    }

}
